package com.tlgen.activity;/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.rxjava.rxlife.RxLife;
import com.tlgen.R;
import com.tlgen.bean.CreditResult;
import com.tlgen.bean.LoginResult;
import com.tlgen.bean.StringResult;
import com.tlgen.bean.SysUser;
import com.tlgen.config.Contants;
import com.tlgen.fragment.LoginFragment;
import com.tlgen.utils.SharedPreferencesUtil;
import com.tlgen.utils.XToastUtils;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xutil.common.StringUtils;

import java.util.HashMap;

import butterknife.OnClick;
import rxhttp.RxHttp;

/**
 * 登录页面
 *
 * @author xuexiang
 * @since 2019-11-17 22:21
 */
public class LoginActivity extends AppCompatActivity {

    // 使用static 不同方法间共享动态局部变量
    private static String currentUuid;

    public String getCurrentUuid() {
        return currentUuid;
    }

    public void setCurrentUuid(String currentUuid) {
        this.currentUuid = currentUuid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 在当前activity中引用fragment
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.login_fragment, new LoginFragment())
                .commit();

        sendGet();

    }

    public void sendGet() {
        RxHttp.get("/captchaImage")
                .asClass(StringResult.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(res -> {
                    // 不需要前缀
                    // String img = "data:image/gif;base64," + res.getImg();
                    String img = res.getImg();
                    String uuid = res.getUuid();
                   // System.out.println(img);
                    Bitmap bitmap = null;
                    byte[]bitmapArray;
                    bitmapArray=Base64.decode(img, Base64.DEFAULT);
                    bitmap=BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    // 设置想要的大小
                    int newWidth = 640;
                    int newHeight = 440;
                    // 计算缩放比例
                    float scaleWidth = ((float) newWidth) / width;
                    float scaleHeight = ((float) newHeight) / height;
                    // 取得想要缩放的matrix参数
                    Matrix matrix = new Matrix();
                    matrix.postScale(scaleWidth, scaleHeight);
                    // 得到新的图片
                    Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
                            true);
                    findViewById(R.id.et_img).setBackground(new BitmapDrawable(newBitmap));
                    findViewById(R.id.et_img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            sendGet();
                        }
                    });

                    System.out.println("get请求中的uuid为: " + uuid);
                    currentUuid = uuid;

                    //成功回调
                }, (error)  -> {
                    //失败回调
                    System.out.println(error);
                });
    }


    private boolean isFirstStart;

    public void postLogin(String code) {
        HashMap<String, Object> map = new HashMap<>();
        System.out.println("当前uuid为: " + currentUuid);

        TextView username = findViewById(R.id.et_username);
        TextView password = findViewById(R.id.et_password);
        RxHttp.postJson("/login")
                .add("username", username.getText().toString())
                .add("password", password.getText().toString())
                .add("code", code)
                .add("uuid", currentUuid)
                .add("contentType", "application/json;charset=UTF-8")
                .asClass(LoginResult.class)
                .to(RxLife.toMain(this))  //感知生命周期，并在主线程回调
                .subscribe(res -> {
                    String msg = res.getMsg();
                    String code1 = res.getCode();
                    String token = res.getToken();
                    System.out.println("返回的token为: " + token);
                    System.out.println("返回的消息为: " + msg);
                    System.out.println("返回的状态码为: " + code1);
                    map.put("code", code1);
                    if ("200".equals(code1)) {
                        XToastUtils.success(R.string.success_message);
                        // 判断 app 是否是第一次安装
                        SharedPreferencesUtil shared = new SharedPreferencesUtil(this, Contants.CONFIG);
                        isFirstStart = shared.getBoolean(Contants.IS_FIRST_START);
                        if(!isFirstStart){
                            //首次安装去引导页
                            startActivity(new Intent(LoginActivity.this, GlideZoomActivity.class));
                        }else {
                            //去主页
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        }
                    } else {
                        sendGet();
                        // 获取当前Activity的view
                        View view = this.getWindow().getDecorView();
                        SnackbarUtils.Short(view, "您输入的验证码有误,请重试!")
                                .messageCenter()
                                .backColor(Color.RED)
                                .show();
                        return;
                    }

                    // 保存当前的用户信息
                    SharedPreferences preferences = getSharedPreferences("login_info", MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("token", token);
                    editor.putString("userName", username.getText().toString());
                    editor.commit();

                    //成功回调
                }, (error) -> {
                    map.put("code", "403");
                    //失败回调
                    System.out.println(error);
                });
    }

}
